//
//  PatientDetailsViewController.m
//  StraightTrain
//
//  Created by mk on 15/11/27.
//  Copyright © 2015年 mk. All rights reserved.
//

#define tableName        @"patient_mr_file"

#import "PatientDetailsViewController.h"
#import "PatienUserData.h"
#import "ChangePatientViewController.h"
#import "PatientAddImagesViewController.h"
#import "IntentionMainViewController.h"//就诊意向
#import "PatientBookingData.h"

@interface PatientDetailsViewController ()<ChangePatientViewControllerDelegate,PatientAddImagesViewControllerDelegate>
{
    PatienUserInfoData * patientInfo;
    PatientBookingInfoData * patientBooking;//病例介绍
    NSMutableArray * arrPictur;
}
@end

@implementation PatientDetailsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    titleLabel.text = self.strTitle;
    if ([self.strTitle isEqualToString:@"患者详情"])
    {
        btnOK.hidden = NO;
    }else
    {
        btnOK.hidden = YES;
    }
    
    [scrollMain setAlwaysBounceVertical:YES];
    patientBooking = [[PatientBookingInfoData alloc]init];
    patientInfo = [[PatienUserInfoData alloc]init];
    arrPictur = [[NSMutableArray alloc]initWithCapacity:0];
    [self loadDate];
    [self loadPicturData];
}

-(void)loadDate
{
     SetHUDStartText(@"加载中..")
    
    NSString * strUrl = [NSString stringWithFormat:@"%@%@?username=%@&token=%@",[gProjConfig.dicAllUrl objectForKey:@"patientinfoUrl"],self.strID,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];
    
    [[HttpClient manager]GET:strUrl
                  parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
          DLog(@"=responseObject:患者详情==%@",responseObject);
         id dateBooking = [[responseObject objectForKey:requestDataKey] objectForKey:@"patientInfo"];
         [patientInfo parseData:dateBooking];

         dateBooking = [[responseObject objectForKey:requestDataKey] objectForKey:@"patientBooking"];
         [patientBooking parseData:dateBooking];
         
        [self setDefaultViewData];
        SetHUDHidden;
         
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
        HUDShowRequestError(error.domain, self.view)
    }];

}

-(void)loadPicturData
{
   // NSString * strUrl = [NSString stringWithFormat:@"%@?tableName=%@&username=%@&token=%@&patientId=%@&reportType=mr",[gProjConfig.dicAllUrl objectForKey:@"fileurl"],tableName,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token],self.strID];
    
    NSString * strUrl = [NSString stringWithFormat:@"%@%@?username=%@&token=%@&reportType=mr", NullObjToString([gProjConfig.dicAllUrl objectForKey:@"patientfileUrl"]),self.strID,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];

    [[HttpClient manager]GET:strUrl
                  parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         DLog(@"==%@",responseObject);
         id requestData = [responseObject objectForKey:requestDataKey];
         if ([requestData isKindOfClass:[NSDictionary class]])
         {
             id files = [requestData objectForKey:@"files"];
             if ([files isKindOfClass:[NSArray class]])
             {
                 arrPictur = [[responseObject objectForKey:requestDataKey] objectForKey:@"files"];
                 [self setPicturView];
             }
         }else if ([requestData isKindOfClass:[NSArray class]])
         {
             arrPictur = [responseObject objectForKey:requestDataKey];
             [self setPicturView];

         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
        HUDShowRequestError(error.domain, self.view)
    }];

}

-(void)setDefaultViewData
{
    /*
     age,ageMonth,birthMonth,birthYear,cityName,dateUpdated,diseaseDetail,diseaseName,gender,id ,mobile,name,stateName
    */
    //用户基本信息姓名|性别|年龄|地址
    labUser.text = [NSString stringWithFormat:@"%@ | %@ | %@岁 | %@",patientInfo.patien_name,patientInfo.patien_gender,patientInfo.patien_age,patientInfo.patien_cityName];
    //用户-病情描述
    labDescription.text = [NSString stringWithFormat:@"病情描述:%@",patientInfo.patien_diseaseDetail];
    btnChangeUser.hidden = NO;

    if (!patientBooking.patien_id)
    {
        for (NSLayoutConstraint *constraints in [viewTravel constraints])
        {
            if (constraints.firstItem == viewTravel && constraints.firstAttribute == NSLayoutAttributeHeight)
            {
                constraints.constant = 0;
                break;
            }
        }
    }else
    {
      //booking
     NSString * strBeg =  [CommonFunctions nianYueRiStringConvertDateString:patientBooking.patien_dateStart withFormatter:@"-"];
     NSString * strEnd = [CommonFunctions nianYueRiStringConvertDateString:patientBooking.patien_dateEnd withFormatter:@"-"];
        
      labTravelTime.text = [NSString stringWithFormat:@"就诊时间:%@至%@",strBeg,strEnd];
      labTravelType.text = patientBooking.patien_travelType;
      labTravelDescription.text =[NSString stringWithFormat:@"%@",patientBooking.patien_detail];
        
        CGRect tmpRect = [labTravelDescription.text boundingRectWithSize:CGSizeMake(APP_CONTENT_WIDTH-20, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName, nil] context:nil];
        
        // 高度H
        CGFloat contentH = tmpRect.size.height;

       // DLog(@"===%f",contentH);
        for (NSLayoutConstraint *constraints in [viewTravel constraints])
        {
            if (constraints.firstItem == viewTravel && constraints.firstAttribute == NSLayoutAttributeHeight)
            {
                constraints.constant = (80+contentH);
                break;
            }
        }
    }
}

#pragma mark 图片View
-(void)setPicturView
{
    for(UIView * imageP in [viewPictur subviews])
    {
        [imageP removeFromSuperview];
    }
    
    int btnWidth = (appScreenWidth-60)/3;
    int row = (int)(arrPictur.count/3);
    if (arrPictur.count%3>0)
    {
        row = (int)(arrPictur.count/3)+1;
    }
   // DLog(@"row=%d",row);
    
    int pickerViewH = 0;
    pickerViewH = (btnWidth*row)+(10*row);
    
    for (NSLayoutConstraint *constraints in [viewPictur constraints])
    {
        if (constraints.firstItem == viewPictur && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            constraints.constant = pickerViewH;
            break;
        }
    }
    
    
    //设置view的高度
    
    int viewWidth = APP_CONTENT_WIDTH;
    
    int btnHeight = (appScreenWidth-50)/3;
    int rowNum = 0;
    int rowRight = 10;
    for (int i = 0; i < [arrPictur count]; i++)
    {
        UIButton *btnMark = [UIButton buttonWithType:UIButtonTypeCustom];
        btnMark.tag = i;
        [btnMark addTarget:self action:@selector(btnLookImage:) forControlEvents:UIControlEventTouchUpInside];
        [btnMark setContentMode:UIViewContentModeScaleAspectFill];
        NSString * strImageUrl = [NSString stringWithFormat:@"%@",[[arrPictur objectAtIndex:i] objectForKey:@"absThumbnailUrl"]];//压缩
       [CommonFunctions setButtonImageWithButton:btnMark iamgePathUrl:strImageUrl];
        
        btnMark.userInteractionEnabled = YES;
        [btnMark setTranslatesAutoresizingMaskIntoConstraints:NO];
        [viewPictur addSubview:btnMark];
        
        NSDictionary *views = NSDictionaryOfVariableBindings(btnMark);
        NSString *sH = [NSString stringWithFormat:@"H:|-%d@1000-[btnMark(%d@1000)]",rowRight,btnWidth];
        [viewPictur addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:sH
                                                                                options:0
                                                                                metrics:nil
                                                                                  views:views]];
        
        NSString *sV = [NSString stringWithFormat:@"V:|-%d@1000-[btnMark(%d@1000)]",rowNum*(btnHeight+10),btnHeight];
        if (i == [arrPictur count]-1)
        {
            sV = [NSString stringWithFormat:@"V:|-%d@1000-[btnMark(%d@1000)]-0@1000-|",rowNum*(btnHeight+10),btnHeight];
        }
        [viewPictur addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:sV
                                                                                options:0
                                                                                metrics:nil
                                                                                  views:views]];
        rowRight += (btnWidth+10.0f);
        if (rowRight+btnWidth > viewWidth) {
            rowRight = 10.0f;
            rowNum++;
        }
    }
    
    [viewPictur.superview layoutIfNeeded];
}

#pragma mark ===查看病例大图图片===
-(void)btnLookImage:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    MFMWPhotoBrowser * browse = [[MFMWPhotoBrowser alloc] init];
    browse.mfDelegate = self;
    browse.delegate = self;
    browse.displayDeleteButton = NO;
    [browse setCurrentPhotoIndex:btn.tag];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browse];
    [self presentViewController:nc animated:YES completion:nil];
    
}


//查看大图
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return arrPictur.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    MWPhoto * photo ;
    
   
    NSString * strUrl = [NSString stringWithFormat:@"%@",[[arrPictur objectAtIndex:index] objectForKey:@"absFileUrl"]];
    photo = [MWPhoto photoWithURL:[NSURL URLWithString:strUrl]];
    return photo;
    
}

     


#pragma mark 修改用户基本信息
-(IBAction)changeUserMessage:(id)sender
{
    ChangePatientViewController * patient = [[ChangePatientViewController alloc]initWithNibName:@"ChangePatientViewController" bundle:nil];
    patient.delegate = self;
    patient.userInfo = patientInfo;
    [self.navigationController pushViewController:patient animated:YES];

}


#pragma mark 修改图片信息
-(IBAction)changePictur:(id)sender
{
    PatientAddImagesViewController * addImage = [[PatientAddImagesViewController alloc]initWithNibName:@"PatientAddImagesViewController" bundle:nil];
    
    addImage.strID = patientInfo.patien_id;
    addImage.strType = @"mr";
    addImage.addCount = (9-arrPictur.count);
    addImage.delegate = self;
    addImage.strTableName = tableName;
    [self.navigationController pushViewController:addImage animated:YES];

}

#pragma mark 创建患者信息
-(IBAction)btnClickPay:(id)sender
{
    IntentionMainViewController * main = [[IntentionMainViewController alloc]initWithNibName:@"IntentionMainViewController" bundle:nil];
    main.strID = self.strID;
    [self.navigationController pushViewController:main animated:YES];
}


-(void)addPictureSuccess
{
    [self loadPicturData];
}


#pragma mark changePatientDataSuccess
-(void)changePatientDataSuccess
{
    [self loadDate];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
